﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using Yu.Cms.Common;
using Yu.Cms.IDAL;

namespace Yu.Cms.SQLServerDAL
{
    public class Comment : IComment
    {
        private readonly string TableName = "Y_Comment";

        #region IComment 成员

        /// <summary>
        /// 添加评论内容
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Add(Yu.Cms.Model.Comment model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into " + TableName + "(");
            strSql.Append("PostID,TypeID,ParentID,CommentEmail,CommentUrl,CommentTitle,bComment,PubTime,PubIp)");
            strSql.Append(" values (");
            strSql.Append("@PostID,@TypeID,@ParentID,@CommentEmail,@CommentUrl,@CommentTitle,@bComment,@PubTime,@PubIp)");
            strSql.Append(";select @@IDENTITY");
            SqlParameter[] parameters = {
					new SqlParameter("@PostID", SqlDbType.Int,4),
                    new SqlParameter("@TypeID",SqlDbType.Int,4),
                    new SqlParameter("@ParentID",SqlDbType.Int,4),                    
					new SqlParameter("@CommentEmail", SqlDbType.NVarChar,100),
					new SqlParameter("@CommentUrl", SqlDbType.NVarChar,50),
					new SqlParameter("@CommentTitle", SqlDbType.NVarChar,100),
					new SqlParameter("@bComment", SqlDbType.NVarChar,1000),
					new SqlParameter("@PubTime", SqlDbType.SmallDateTime),
					new SqlParameter("@PubIp", SqlDbType.VarChar,15)
					};
            parameters[0].Value = model.PostID;
            parameters[1].Value = model.TypeID;
            parameters[2].Value = model.ParentID;
            parameters[3].Value = model.CommentEmail;
            parameters[4].Value = model.CommentUrl;
            parameters[5].Value = model.CommentTitle;
            parameters[6].Value = model.bComment;
            parameters[7].Value = model.PubTime;
            parameters[8].Value = model.PubIp;

            object obj = DbHelperMsSQL.GetSingle(strSql.ToString(), parameters);
            if (obj == null)
            {
                return -1;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        /// <summary>
        /// 管理员添加回复内容
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Update(Yu.Cms.Model.Comment model)
        {
           // StringBuilder strSql = new StringBuilder();
           // strSql.Append("update " + TableName + " set ");   
           // strSql.Append("ReComment=@ReComment,");
           // strSql.Append("RePubTime=@RePubTime");
           // strSql.Append(" where CommentID=@CommentID ");
           // SqlParameter[] parameters = {
           //         new SqlParameter("@CommentID", SqlDbType.Int,4),					
           //         new SqlParameter("@ReComment", SqlDbType.NVarChar,1000),
           //         new SqlParameter("@RePubTime", SqlDbType.SmallDateTime)};
           // parameters[0].Value = model.CommentID;
           // parameters[1].Value = model.PostID;
           // parameters[2].Value = model.Commenter;          

           //return  DbHelperMsSQL.ExecuteSql(strSql.ToString(), parameters);
            return 0;
        }

        /// <summary>
        /// 删除评论内容
        /// </summary>
        /// <param name="CommentID"></param>
        /// <returns></returns>
        public int Delete(int CommentID)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from  " + TableName);
            strSql.Append(" where CommentID=@CommentID ");
            SqlParameter[] parameters = {
					new SqlParameter("@CommentID", SqlDbType.Int,4)};
            parameters[0].Value = CommentID;

            return DbHelperMsSQL.ExecuteSql(strSql.ToString(), parameters);
        }

        /// <summary>
        /// 获取该CommentID单条记录
        /// </summary>
        /// <param name="CommentID"></param>
        /// <returns></returns>
        public Yu.Cms.Model.Comment GetModelByCID(int CommentID)
        {
            Yu.Cms.Model.Comment fam = new Yu.Cms.Model.Comment();
            QueryParam qp=new QueryParam();
            qp.Where= " Where And CommentID="+CommentID;
            int RecordCount;
            IList<Yu.Cms.Model.Comment> lst = this.GetList(qp, out RecordCount);
            if (lst.Count > 0)
            {
                fam = lst[0];
            }
            return fam;
        }

        /// <summary>
        /// 依据PostID获取单条实体类
        /// </summary>
        /// <param name="CommentID"></param>
        /// <returns></returns>
        public Yu.Cms.Model.Comment GetModelByPostID(int PostID)
        {
            Yu.Cms.Model.Comment fam = new Yu.Cms.Model.Comment();
            QueryParam qp = new QueryParam();
            qp.Where = " Where  ParentID=0 And PostID=" + PostID;
            int RecordCount;
            IList<Yu.Cms.Model.Comment> lst = this.GetList(qp, out RecordCount);
            if (lst.Count > 0)
            {
                fam = lst[0];
            }
            return fam;
        }


        /// <summary>
        /// 判断是否有评论
        /// </summary>
        /// <param name="PostID"></param>
        /// <param name="cTypeID">类型ID，评论or图片</param>
        /// <returns></returns>
        public bool isCommentByPostID(int PostID, Yu.Enum.CTypeID cTypeID)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * from " + TableName );
            strSql.AppendFormat(" Where PostID={0} And TypeID={1}", PostID, (int)cTypeID);
            return DbHelperMsSQL.Exists(strSql.ToString());
        }


        /// <summary>
        /// 统计评论的数目
        /// </summary>
        /// <param name="PostID">PostID</param>
        /// <returns></returns>
        public int GetCommentCount(int PostID)
        {
            string _where = " Where PostID=" + PostID;
            return DbHelperMsSQL.GetMaxCount(TableName, _where);
        }

        /// <summary>
        /// 根据文章PostID获取评论列表（带分页）
        /// </summary>
        /// <param name="PostID">文章ID</param>
        /// <param name="CurrentPageIndex"></param>
        /// <param name="PageSize"></param>
        /// <param name="RecordCount"></param>
        /// <returns></returns>
        public IList<Yu.Cms.Model.Comment> GetList(int PostID, int CurrentPageIndex, int PageSize, out int RecordCount)
        {
            QueryParam qp = new QueryParam();
            qp.PageIndex = CurrentPageIndex;
            qp.PageSize = PageSize;
            qp.Where = string.Format(" Where PostID={0} And ParentID = 0", PostID); //暂时只实现一级评论            
            return this.GetList(qp, out RecordCount);
        }

        /// <summary>
        /// 获取ParentID=CommentID子列表
        /// </summary>
        /// <param name="CommentID"></param>
        /// <returns></returns>
        public IList<Yu.Cms.Model.Comment> GetChildList(int CommentID)
        {
            int RecordCount = 0;
            QueryParam qp = new QueryParam();
            qp.Where = " Where ParentID=" + CommentID;
            IList<Yu.Cms.Model.Comment> lst = this.GetList(qp, out RecordCount);
            for (int i = 0; i < lst.Count; i++)
            {
                if (this.isExistChild(lst[i].CommentID))
                {
                    lst.Add(this.GetChildList(lst[i].CommentID)[i]);
                }
            }
            return lst;
        }

        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="CommentID"></param>
        /// <returns></returns>
        protected bool isExistChild(int CommentID)
        {
            StringBuilder Builder = new StringBuilder();
            Builder.Append("select * from " + TableName);
            Builder.Append(" Where ParentID =" + CommentID);
            return DbHelperMsSQL.Exists(Builder.ToString());
        }

        /// <summary>
        /// 根据获取最新评论列表
        /// </summary>
        /// <param name="iTop">首页显示iTop条</param>
        /// <returns></returns
        public IList<Yu.Cms.Model.Comment> GetNewList(int iTop)
        {
            QueryParam qp = new QueryParam();
            qp.PageIndex = 1;
            qp.PageSize = iTop;
            qp.OrderType = 1;
            int RecordCount = 0;
            return this.GetList(qp, out RecordCount);
        }

        #endregion



        /// <summary>
        /// 返回Comment实体类的IList对象 (Y_Comment)
        /// </summary>
        /// <param name="qp">查询类(非安全函数,传入参数请进行Sql字符串过滤)</param>
        /// <param name="RecordCount">返回记录总数</param>
        /// <returns>Comment实体类的IList对象(Y_Comment)</returns>
        public IList<Yu.Cms.Model.Comment> GetList(QueryParam qp, out int RecordCount)
        {
            qp.TableName = TableName;            
            if (qp.Orderfld == null)
            {
                qp.Orderfld = "CommentID";
            }
            else if (qp.Orderfld != "CommentID")
            {
                qp.Orderfld += ",CommentID";
            }

            if (qp.ReturnFields == null)
            {
                qp.ReturnFields = "*";
            }
            else
            {
                qp.ReturnFields += ",";
                qp.ReturnFields += qp.Orderfld;
            }            
            DbHelperMsSQL.PopulateDelegate<Yu.Cms.Model.Comment> mypd = new DbHelperMsSQL.PopulateDelegate<Yu.Cms.Model.Comment>(this.Populate_Comment);
            return DbHelperMsSQL.GetRecordListBySql(mypd, qp, out RecordCount);
        }

        /// <summary>
        /// 将记录集转为Y_Comment实体类 (Y_Comment)
        /// </summary>
        /// <param name="dr">记录集</param>
        /// <param name="Fileds">字段名列表</param>
        /// <returns>Y_Comment</returns>
        protected Yu.Cms.Model.Comment Populate_Comment(IDataReader dr, Dictionary<string, string> Fileds)
        {
            Yu.Cms.Model.Comment nc = new Yu.Cms.Model.Comment();
            if (Fileds.ContainsKey("CommentID") && !Convert.IsDBNull(dr["CommentID"])) nc.CommentID = Convert.ToInt32(dr["CommentID"]); // 自动ID
            if (Fileds.ContainsKey("PostID") && !Convert.IsDBNull(dr["PostID"])) nc.PostID = Convert.ToInt32(dr["PostID"]); // 与commentid关联
            if (Fileds.ContainsKey("TypeID") && !Convert.IsDBNull(dr["TypeID"])) nc.TypeID = Convert.ToInt32(dr["TypeID"]); // 评论类型  1:文章 2:图片
            if (Fileds.ContainsKey("ParentID") && !Convert.IsDBNull(dr["ParentID"])) nc.ParentID = Convert.ToInt32(dr["ParentID"]); // 关联文章ID
            if (Fileds.ContainsKey("CommentEmail") && !Convert.IsDBNull(dr["CommentEmail"])) nc.CommentEmail = Convert.ToString(dr["CommentEmail"]).Trim(); // 评论人Email
            if (Fileds.ContainsKey("CommentUrl") && !Convert.IsDBNull(dr["CommentUrl"])) nc.CommentUrl = Convert.ToString(dr["CommentUrl"]).Trim(); // 评论人URL
            if (Fileds.ContainsKey("CommentTitle") && !Convert.IsDBNull(dr["CommentTitle"])) nc.CommentTitle = Convert.ToString(dr["CommentTitle"]).Trim(); // 评论标题
            if (Fileds.ContainsKey("bComment") && !Convert.IsDBNull(dr["bComment"])) nc.bComment = Convert.ToString(dr["bComment"]).Trim(); // 评论内容
            if (Fileds.ContainsKey("PubTime") && !Convert.IsDBNull(dr["PubTime"])) nc.PubTime = Convert.ToDateTime(dr["PubTime"]); // 评论时间
            if (Fileds.ContainsKey("PubIp") && !Convert.IsDBNull(dr["PubIp"])) nc.PubIp = Convert.ToString(dr["PubIp"]).Trim(); // 评论IP
            return nc;
        }
    }
}
